package it.carlom.stikkyheader.core;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.app.Context;

public abstract class StikkyHeader {
    /***
     * 上下文
     */
    protected Context mContext;
    /**
     * 粘性的头部view
     */
    protected Component mHeader;
    /**
     * 头部显示的最低高度
     */
    protected int mMinHeightHeader;
    private final HeaderAnimator mHeaderAnimator;
    /**
     * 头部view 的高度
     */
    protected int mHeightHeader;
    private Component.TouchEventListener onTouchListenerOnHeaderDelegate;
    private boolean mAllowTouchBehindHeader;

    protected StikkyHeader(Context context, Component header, int minHeightHeader, HeaderAnimator headerAnimator) {
        mContext = context;
        mHeader = header;
        mMinHeightHeader = minHeightHeader;
        mHeaderAnimator = headerAnimator;
    }

    public void setOnTouchListenerOnHeaderDelegate(Component.TouchEventListener onTouchListenerOnHeaderDelegate) {
        this.onTouchListenerOnHeaderDelegate = onTouchListenerOnHeaderDelegate;
    }

    protected abstract Component getScrollingView();

    /**
     * Init method called when the StikkyHeader is created
     */
    protected void init() {
        measureHeaderHeight();
        setupAnimator();
    }

    void build(boolean allowTouchBehindHeader) {
        mAllowTouchBehindHeader = allowTouchBehindHeader;
        setOnTouchListenerOnHeader(onTouchListenerOnHeaderDelegate);
        init();
    }

    private void measureHeaderHeight() {
        int height = mHeader.getHeight();

        if (height == 0) {
            ComponentContainer.LayoutConfig layoutConfig = mHeader.getLayoutConfig();
            if (layoutConfig != null) {
                height = layoutConfig.height;
            }
        }

        if (height > 0) {
            setHeightHeader(height);
        }
        mHeader.setLayoutRefreshedListener(component -> {
            if (mHeightHeader != mHeader.getHeight()) {
                setHeightHeader(mHeader.getHeight());
            }
        });
    }

    protected void setHeightHeader(final int heightHeader) {
        mHeightHeader = heightHeader;
        mHeaderAnimator.setHeightHeader(heightHeader, mMinHeightHeader);
    }

    public void onScroll(int yScroll) {
        mHeaderAnimator.onScroll(yScroll);
    }

    /**
     * 设置头部view动画
     */
    protected void setupAnimator() {
        mHeaderAnimator.setupAnimator(mHeader);
    }

    public void setMinHeightHeader(int minHeightHeader) {
        this.mMinHeightHeader = minHeightHeader;
        mHeaderAnimator.setHeightHeader(mHeightHeader, mMinHeightHeader);
    }

    public void setOnTouchListenerOnHeader(Component.TouchEventListener onTouchListenerOnHeaderDelegate) {
        StikkyHeaderUtils.setOnTouchListenerOnHeader(mHeader, getScrollingView(), onTouchListenerOnHeaderDelegate, mAllowTouchBehindHeader);
    }

    public Component getHeader() {
        return mHeader;
    }
}
